<template>
  <el-upload
    class="upload-wrapper"
    v-model:file-list="fileList"
    :action="`${baseUrl}/upload`"
    :limit="limit"
    name="files"
    :headers="headers"
    accept="application/pdf, .mp4"
    v-bind="attrs"
    :before-upload="handleBeforeUpload"
    :on-exceed="handleExceed"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :on-success="handleSuccess"
    :on-error="handleError"
  >
    <template #default>
      <slot>
        <template v-if="uploadAttrs['list-type'] === 'text'">
          <el-button type="primary" icon="upload" :disabled="fileList.length >= limit">点击上传</el-button>
        </template>
        <template v-else>
          <el-icon><Plus /></el-icon>
        </template>
      </slot>
    </template>
    <template #tip>
      <slot name="tip"></slot>
    </template>
  </el-upload>
</template>

<script setup>
import { ElMessage, ElLoading } from 'element-plus'

const props = defineProps({
  // 上传数量
  limit: { type: Number, default: 1 },
})
// 格式为 ['', '']，或者 ''
const model = defineModel({ type: [Array, String], default: '' })

const baseUrl = import.meta.env.VITE_APP_API
const headers = {
  Authorization: localStorage.getItem('token'),
}

const attrs = useAttrs()

const uploadAttrs = computed(() => {
  return {
    'list-type': 'text',
    ...attrs,
  }
})

const fileList = ref([])

watch(
  () => model.value,
  newValue => {
    if (typeof newValue === 'string' && newValue) {
      fileList.value = [{ name: newValue, url: newValue }]
    } else if (Array.isArray(newValue)) {
      if (newValue.length > 0) {
        fileList.value = newValue.map(item => {
          return {
            name: item,
            url: item,
          }
        })
      }
    }
  },
  { immediate: true }
)

let loadingInstance = null

const handleBeforeUpload = () => {
  loadingInstance = ElLoading.service({ fullscreen: true, background: 'rgba(0, 0, 0, 0.7)', text: '上传中...' })
  return true
}

const handleExceed = () => {
  ElMessage({
    type: 'warning',
    message: `最多上传${props.limit}个文件,请先删除已上传的文件`,
  })
}

const handlePreview = UploadFile => {
  if (UploadFile.status !== 'success') {
    return
  }
  window.open(UploadFile.url, '_blank')
}

const handleSuccess = (response, UploadFile, UploadFiles) => {
  if (props.limit == 1) {
    model.value = response.data[0].url
  } else {
    model.value = UploadFiles.map(item => item.url || item.response.data[0].url)
  }

  loadingInstance?.close()
}
const handleError = response => {
  ElMessage.error('上传失败')
  loadingInstance?.close()
}
const handleRemove = (UploadFile, UploadFiles) => {
  if (props.limit === 1) {
    model.value = UploadFiles?.[0] ?? ''
  } else {
    model.value = UploadFiles.map(item => item.url || item.response.data[0].url)
  }
}
</script>

<style lang="scss" scoped>
.upload-wrapper {
  width: 100%;
  :deep(.el-upload-list__item .el-progress) {
    top: -10px;
    left: 0;
  }
  :deep(.el-icon--close-tip) {
    display: none !important;
  }
}
</style>
